package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Follow;
import com.hmdp.entity.User;
import com.hmdp.mapper.FollowMapper;
import com.hmdp.service.IFollowService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.UserHolder;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class FollowServiceImpl extends ServiceImpl<FollowMapper, Follow> implements IFollowService {

    private final StringRedisTemplate stringRedisTemplate ;
    private final IUserService userService ;

    /**
     * 关注或取关
     *
     * @param followUserId
     * @param isFollow
     */
    @Override
    public void follow(Long followUserId, Boolean isFollow) {
        // 获取登录用户
        Long userId = UserHolder.getUser().getId();
        // 判断关注还是取关
        if (isFollow) {
            // 关注 新增数据
            Follow follow = Follow.builder()
                    .createTime(LocalDateTime.now())
                    .followUserId(followUserId)
                    .userId(userId)
                    .build();
            // 保存
            boolean success = this.save(follow);
            if (success) {
                // 每个用户维护一个自己关注的人的集合
                String key = RedisConstants.FOLLOW_KEY + userId ;
                stringRedisTemplate.opsForSet().add(key, followUserId.toString()) ;
            }
        } else {
            // 取关 删除数据
            boolean success = this.remove(new QueryWrapper<Follow>().eq("user_id", userId).eq("follow_user_id", followUserId));
            if (success) {
                // 每个用户维护一个自己关注的人的集合
                String key = RedisConstants.FOLLOW_KEY + userId ;
                stringRedisTemplate.opsForSet().remove(key, followUserId.toString()) ;
            }
        }
    }

    /**
     * 查看共同关注
     *
     * @param id
     */
    @Override
    public List<UserDTO> followCommons(Long id) {
        // 获取登录用户
        Long userId = UserHolder.getUser().getId();
        String key1 = RedisConstants.FOLLOW_KEY + userId ;
        // 求交集
        String key2 = RedisConstants.FOLLOW_KEY + id ;
        Set<String> intersect = stringRedisTemplate.opsForSet().intersect(key1, key2);
        if (intersect == null || intersect.isEmpty()) {
            return Collections.emptyList() ;
        }
        // 解析 id
        List<Long> ids = intersect.stream().map(Long::valueOf).collect(Collectors.toList());
        // 查询用户
        List<User> userList = userService.listByIds(ids);
        // 共同关注列表
        List<UserDTO> userDTOList = userList.stream()
                .map(user -> BeanUtil.copyProperties(user, UserDTO.class))
                .collect(Collectors.toList());
        return userDTOList ;
    }

    /**
     * 判断是否关注
     *
     * @param followUserId
     * @return
     */
    @Override
    public Boolean isFollow(Long followUserId) {
        // 获取登录用户
        Long userId = UserHolder.getUser().getId();
        // 查询是否关注
        Integer count = this.query()
                .eq("user_id", userId)
                .count();
        // 返回
        return count > 0;
    }
}
